package com.zzyl.intercept;

import com.zzyl.constant.Constants;
import com.zzyl.enums.BasicEnum;
import com.zzyl.exception.BaseException;
import com.zzyl.properties.JwtProperties;
import com.zzyl.utils.JwtUtil;
import com.zzyl.utils.UserThreadLocal;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@Component
@Slf4j
public class WechatUserInterceptor implements HandlerInterceptor {
    @Autowired
    private JwtProperties jwtProp;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String path = request.getRequestURI();
        log.info("path:{}",path);
        if ("/customer/user/login".equals(path)){
            return true;
        }
        String token = request.getHeader("authorization");
        if (token.isBlank()){
            log.error("token为空");
            throw new BaseException(BasicEnum.LOGIN_LOSE_EFFICACY);
        }
        Map<String,Object> claims = JwtUtil.parseJWT(jwtProp.getBase64EncodedSecretKey(), token);
        log.info("claims:{}",claims);
        UserThreadLocal.set(Long.valueOf(claims.get(Constants.JWT_USERID).toString()));
        log.info(UserThreadLocal.getUserId().toString());
        UserThreadLocal.setSubject(claims.get(Constants.JWT_USERNAME).toString());
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserThreadLocal.remove();
        UserThreadLocal.removeSubject();
    }
}
